
<template>
  <div>
    <div v-if="$route.path===$store.state.loginPath">
      <router-view ></router-view>
    </div>

    <div v-if="$route.path!==$store.state.loginPath">
      <el-container>
        <el-header  class="base-header">
          <el-row >
            <el-col style="width: 40px;padding: 5px 0px 0px 0px">
              <el-button type="primary" @click="collapseNav" icon="el-icon-menu" size="mini"></el-button>
            </el-col>
            <el-col :span="11" style="font-size: 20px;padding: 6px 0px 0px 10px;color: #fff">ERP系统</el-col>
            <el-col style="width:200px;text-align:right; float:right; padding: 6px 0px 0px 0px">
              <el-dropdown @command="handleCommand">
                          <span class="el-dropdown-link">
                              {{$store.state.sessionUser.orgName}}-{{$store.state.sessionUser.userName}}
                              <i class="el-icon-arrow-down el-icon--right"></i>
                          </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="resetPwd">修改密码</el-dropdown-item>
                  <el-dropdown-item command="exit">退出</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </el-header>
        <el-container class="main-container" :style="$store.state.conHeight" >
          <el-aside :width="navWidth"  class="base-aside">
            <el-menu
                    :default-active="$store.state.activeMenu.path" :default-openeds="openeds"
                    background-color="#545c64"
                    text-color="#fff"
                    active-text-color="#fff"
                    :collapse="isNavCollapse"
                    @select="selectMenu"
                    @open="handleOpen"
                    @close="handleClose">

              <template v-for="(item,index1) in $store.state.menuList">

                <el-submenu  v-if="item.children!=null" :key="item.id" :index="item.menuName">
                  <template slot="title">
                    <i v-if="item.icon!==''" :class="item.icon"></i>
                    <span>{{item.menuName}}</span>
                  </template>

                  <template v-for="(item2,index2) in item.children">
                    <!--三级菜单-->
                    <el-submenu v-if="item2.children!=null"  :index="item2.id" :key="index2">
                      <template slot="title">
                        <i v-if="item2.icon!==''" :class="item2.icon"></i>
                        {{item2.menuName}}
                      </template>
                      <template  v-for="(item3,index3) in item2.children">
                        <el-menu-item :index = "item3.fullUrl" :key = "index3"
                                      :id="item3.id" :menuName="item3.menuName" :appCode="item3.appCode" :frame="item3.frame" >
                          <i v-if="item3.icon!==''" :class="item3.icon"></i>
                          {{item3.menuName}}
                        </el-menu-item>
                      </template>
                    </el-submenu>
                    <!--二级菜单-->
                    <el-menu-item v-else :index = "item2.fullUrl" :key = "index2"
                                  :id="item2.id" :menuName="item2.menuName" :appCode="item2.appCode" :frame="item2.frame"   >
                      <i v-if="item2.icon!==''" :class="item2.icon"></i>
                      {{item2.menuName}}
                    </el-menu-item>
                  </template>
                </el-submenu>

                <!--一级菜单-->
                <el-menu-item v-else :index = "item.fullUrl" :key = "index1"
                              :id="item.id" :menuName="item.menuName" :appCode="item.appCode" :frame="item.frame"   >
                  <i v-if="item.icon!==''" :class="item.icon"></i>
                  {{item.menuName}}
                </el-menu-item>

              </template>
            </el-menu>
          </el-aside>

          <el-main class="base-main"  >

              <div  class="base-top-tabs" >

                <el-tabs
                        v-model="$store.state.activeMenu.path"
                        type="border-card"
                        @contextmenu.prevent.native="openContextMenu"
                        @tab-click='tabClick'
                        @tab-remove='tabRemove'>
                  <el-tab-pane
                               :key="$store.state.homeMenu.menuName"
                               :label="$store.state.homeMenu.menuName" :id="$store.state.homeMenu.id" :path="'/'+$store.state.homeMenu.appCode+$store.state.homeMenu.path"
                               :menuName="$store.state.homeMenu.menuName"   :appCode="$store.state.homeMenu.appCode"  :compo="$store.state.homeMenu.compo"
                               :frame="$store.state.homeMenu.frame"
                               :name="$store.state.homeMenu.path"
                               :closable="false">
                  </el-tab-pane>
                  <el-tab-pane
                          v-for="(item, index) in $store.state.openTab"
                          :key="item.menuName" :closable="true"  :ref="'tab_'+item.id"
                          :label="item.menuName" :id="item.id" :path="item.path" :menuName="item.menuName"   :appCode="item.appCode"  :compo="item.compo" :frame="item.frame"
                          :name="item.path">
                  </el-tab-pane>
                </el-tabs>
              </div>

              <div class="content-wrap"  ref="wrap"  >
                <keep-alive :include="$store.state.viewIncludes"  >
                  <router-view ></router-view>
                </keep-alive>
              </div>
              <!--qiankun dom-->
              <div :id="item.domID" v-show="$store.state.activeMenu.frame"  v-for="item in $store.state.microConfigList"></div>

          </el-main>
        </el-container>
      </el-container>

      <div v-show="contextMenuVisible">
        <ul :style="{left:left+'px',top:top+'px'}" class="contextmenu">
          <li><el-button type="text" @click="curTabReload()" size="mini">重新加载</el-button></li>
          <li><el-button type="text" @click="closeAllTabs()" size="mini">关闭所有</el-button></li>
          <li><el-button type="text" @click="closeOtherTabs('left')" :disabled="isDisabledCloseLeftBtnFlag" size="mini">关闭左边</el-button></li>
          <li><el-button type="text" @click="closeOtherTabs('right')" :disabled="isDisabledCloseRightBtnFlag" size="mini">关闭右边</el-button></li>
          <li><el-button type="text" @click="closeOtherTabs('other')" size="mini">关闭其他</el-button></li>
        </ul>
      </div>

      <reset_pwd :visible.sync="pwdVisible"  ref="pwdRef"  ></reset_pwd>
    </div>

  </div>
</template>

<script>
  import reset_pwd from './page/user/reset_pwd.vue'
  import Axios from "axios";
  import {loadMicroApp} from "./qiankun";
  import router from "./router";
  import store from "./store";
  export default {
    name:'index',
    components: {
      reset_pwd,
    },

    created(){
      let _this=this;
      let currentPath=_this.$route.path;
      if (currentPath!==_this.$store.state.loginPath){
        let userMsg=localStorage.getItem("userMsg");
        let userMenu=localStorage.getItem("userMenu");
        if (userMsg){
          console.log("从localstorage恢复用户和菜单")
          _this.$store.dispatch("setSessionUser",JSON.parse(userMsg));
          _this.$store.dispatch("setMenuList",JSON.parse(userMenu));
          Axios.defaults.headers={'token':_this.$store.state.sessionUser.token}
        }else{
          _this.$message.error("加载用户&菜单数据错误");
        }
      }
    },
    mounted() {
      let _this=this;
        //设置数据
        setTimeout(function() {
          let currentPath=_this.$route.path;
          console.log("currentPath",currentPath)
          if (currentPath!==_this.$store.state.loginPath){
            let userMenu=localStorage.getItem("userMenu");
            let userMicro=localStorage.getItem("userMicro");
            if (userMenu){
              console.log("从localstorage恢复用户和菜单");
              _this.$store.dispatch("setMenuList",JSON.parse(userMenu));
            }else{
              _this.$message.error("加载用户&菜单数据错误");
            }

            if (userMicro && userMicro !== "undefined"){
              _this.$store.dispatch("setMicroConfigList",JSON.parse(userMicro));
              console.log("设置微服务")
              for (let microConf of _this.$store.state.microConfigList) {
                const micro = _this.$loadMicroApp({...microConf,router})
                _this.$store.commit('addMicro',{activeRule:microConf.activeRule,micro:micro});
                _this.$store.commit('setCurrentMicro',microConf);
              }
            }

            let userHome=localStorage.getItem("userHome");
            if (userHome){
              _this.$store.commit("setHomeMenu",JSON.parse(userHome));
            }

            //事件绑定
            let tab_top_dom = document.body.getElementsByClassName("el-tabs__header is-top")
            tab_top_dom[0].oncontextmenu = _this.openContextMenu
            window.addEventListener("click", _this.clickEvent);

          }
          //_this.initAppData();
          //设置当前菜单
          if (currentPath!==_this.$store.state.loginPath && currentPath!==_this.$store.state.homeMenu.path){
            if (_this.$store.state.activeMenu.path!==currentPath){
              let compo=_this.getCompo(currentPath);
              //设置tab
              let menu=_this.findMenuByPath(currentPath,_this.$store.state.menuList);
              if (menu){
                let menuData={id:menu.id,menuName:menu.menuName,path:currentPath,appCode:menu.appCode,compo:compo,frame:menu.frame,operations:menu.operations};
                _this.$store.commit('addTabs', menuData);
                _this.$store.commit('setActiveMenu', JSON.parse(JSON.stringify(menuData)));
                _this.$actions.setGlobalState({activeMenu: JSON.parse(JSON.stringify(menuData)),reload:false});
              }else{
                console.warn("未找到路径 "+currentPath+"的菜单");
                _this.toHome();

              }
            }
          }else if(currentPath===_this.$store.state.homeMenu.path){
            _this.toHome();
          }
          _this.$store.dispatch("setConHeightForMain");
          _this.ifmHeight=_this.$store.state.clientHeight-_this.topHeight;
        }, 100);
      window.onresize = function(){
        _this.$store.state.clientWidth = document.documentElement.clientWidth;
        _this.$store.state.clientHeight = document.documentElement.clientHeight;
        _this.$store.state.innerWidth = window.innerWidth;
        _this.$store.state.innerHeight = window.innerHeight;
      };
    },
    data() {
      return {
        pwdVisible:false,

        mainHeight:600,
        topHeight:70,
        ifmHeight:400,
        isNavCollapse:false,
        navWidth:'200px',
        openeds:[],

        homeRote:'/home',

        isDisabledCloseLeftBtnFlag:false,
        isDisabledCloseRightBtnFlag:false,
        left:0,
        top:0,
        contextMenuVisible:false,

      }
    },

    methods: {

      refreshPage () {
        let _this=this;
        let activeMenu=this.$store.state.activeMenu;

        if (activeMenu.frame===2){//
          console.log("触发微应用刷新")
          _this.$actions.setGlobalState({activeMenu: activeMenu,reload:true});
        }else{
          console.log("触发基座刷新")
          _this.$store.commit('deleteViewIncludes', activeMenu.compo);
          _this.$router.push({path: '/blank'});//跳到空白
          this.$nextTick(() => {
            _this.$router.push({path: activeMenu.path});
            _this.$store.commit('addViewIncludes', activeMenu.compo);

          })
        }
      },

      selectMenu(index,indexPath,menu){
        let _this=this;
        let frame=menu.$attrs.frame;
        let appCode=menu.$attrs.appCode;
        let menuName=menu.$attrs.menuName;
        let path=index;
        let id=menu.$attrs.id;

        let compo=_this.getCompo(path)
        //路由跳转
        if (id!==_this.$store.state.activeMenu.id){
          _this.$router.push({path: path});
        }
        //设置tab
        let tab = _this.$store.state.openTab.find(item => item.id===id);
        if(!tab && path!==_this.$store.state.homeMenu.path){//非首页,新建TAB
          let _menu=_this.findMenuByPath(path,_this.$store.state.menuList);
          let operations=null;
          if (null!=_menu){
            operations=_menu.operations;
          }
          let menuData={id:id,menuName:menuName,path:path,appCode:appCode,compo:compo,frame:frame,operations:operations};
          _this.$store.commit('addTabs', menuData);
          _this.$store.commit('setActiveMenu', JSON.parse(JSON.stringify(menuData)));
          let globalState={
            activeMenu: JSON.parse(JSON.stringify(menuData)),
            reload:false,
            openTab:_this.$store.state.openTab,
          }
          _this.$actions.setGlobalState(globalState);
        }else if(path===_this.$store.state.homeMenu.path){//首页 切换到首页
          _this.toHome();
        }else{//非首页，切换TAB
          _this.$store.commit('setActiveMenu', JSON.parse(JSON.stringify(tab)));
          let globalState={
            activeMenu: JSON.parse(JSON.stringify(tab)),
            reload:false,
            openTab:_this.$store.state.openTab,
          }
          _this.$actions.setGlobalState(globalState);//tab切换 给子应用传值
        }
        console.log("menu check",path);

      },

      tabClick(tab){
        let _this=this;
        let id=tab.$attrs.id;
        let appCode=tab.$attrs.appCode;
        let path=tab.$attrs.path;
        let frame=tab.$attrs.frame;
        let compo=tab.$attrs.compo;
        let menuName=tab.$attrs.menuName;

        let _menu=_this.findMenuByPath(path,_this.$store.state.menuList);
        let operations=null;
        if (null!=_menu){
          operations=_menu.operations;
        }
        let menuData={id:id,menuName:menuName,path:path,appCode:appCode,compo:compo,frame:frame,operations:operations};

        let currentPath=_this.$route.path;
        if (currentPath===_this.$store.state.activeMenu.path){
          return ;
        }
        _this.$store.commit('setActiveMenu', JSON.parse(JSON.stringify(menuData)));
        let globalState={
          activeMenu: JSON.parse(JSON.stringify(menuData)),
          reload:false,
          openTab:_this.$store.state.openTab,
        }
        _this.$actions.setGlobalState(globalState);
        this.$router.push({path: path});
        console.log('tab check',menuData);
      },
      //移除tab标签
      tabRemove(targetName){
        let _this=this;
        console.log("tabRemove",targetName);
        if (targetName===_this.$store.state.homeMenu.path){
          _this.$message.error("home不可删除");
          return;
        }
        _this.$store.commit('deleteTabs', targetName);

        if (_this.$store.state.activeMenu.path === targetName) {
          // 设置当前激活的路由
          if (_this.$store.state.openTab && _this.$store.state.openTab.length >= 1) {
            let menuData=_this.$store.state.openTab[_this.$store.state.openTab.length-1];
            _this.$store.commit('setActiveMenu', JSON.parse(JSON.stringify(menuData)));
            _this.$router.push({path:menuData.path});
            //_this.$actions.setGlobalState({activeMenu: JSON.parse(JSON.stringify(menuData)),reload:false});
            let globalState={
              activeMenu: JSON.parse(JSON.stringify(menuData)),
              reload:false,
              openTab:_this.$store.state.openTab,
            }
            _this.$actions.setGlobalState(globalState);
          } else {
            _this.toHome();
          }
        }else{
          _this.toHome();
        }

      },

      openContextMenu(e) {
        e.preventDefault(); //防止默认菜单弹出
        let obj = e.srcElement ? e.srcElement : e.target;
        if (obj.id) {
          let curIndex = 0;
          for(;curIndex<this.$store.state.openTab.length;++curIndex){
            if(this.$store.state.openTab[curIndex].path === this.$store.state.activeMenu.path){
              break;
            }
          }
          if(curIndex<=0){
            this.isDisabledCloseLeftBtnFlag = true
            this.isDisabledCloseRightBtnFlag = false
          }else if(curIndex >= this.$store.state.openTab.length-1){
            this.isDisabledCloseLeftBtnFlag = false
            this.isDisabledCloseRightBtnFlag = true
          }else{
            this.isDisabledCloseLeftBtnFlag = false
            this.isDisabledCloseRightBtnFlag = false
          }
          this.contextMenuVisible = true;
          this.left = e.clientX;
          this.top = e.clientY + 10;
        }
      },
      curTabReload(){
        this.refreshPage();
        this.closeContextMenu()
      },

      closeAllTabs() {
        this.$store.commit('setTabs',[]);
        this.$store.commit('cleanViewIncludes');

        this.closeContextMenu();

        this.$store.commit('setActiveMenu',this.$store.state.homeMenu);
        this.$router.push({path:this.$store.state.homeMenu.path});

        let globalState={
          openTab:this.$store.state.openTab,
        }
        this.$actions.setGlobalState(globalState);
      },
      closeOtherTabs(par) {
        if (par === "left") {
          let index = 0;
          for (let option of this.$store.state.openTab) {
            if (option.path === this.$store.state.activeMenu.path) {
              break;
            }
            index++;
          }
          this.$store.commit('spliceTabsByIndex',{start:0,end:index});
        }
        if (par === "right") {
          let index = 0;
          for (let option of this.$store.state.openTab) {
            if (option.path === this.$store.state.activeMenu.path) {
              break;
            }
            index++;
          }
          this.$store.commit('spliceTabsByIndex',{start:index+1,end:this.$store.state.openTab.length});

        }
        if (par === "other") {
          let index = 0;
          for (let option of this.$store.state.openTab) {
            if (option.path === this.$store.state.activeMenu.path) {
              break;
            }
            index++;
          }
          let left=index;
          let right=this.$store.state.openTab.length;
          this.$store.commit('spliceTabsByIndex',{start:0,end:left});
          this.$store.commit('spliceTabsByIndex',{start:1,end:right});
        }
        let globalState={
          openTab:this.$store.state.openTab,
        }
        this.$actions.setGlobalState(globalState);
        this.closeContextMenu()
      },
      closeContextMenu() {
        this.contextMenuVisible = false;
      },
      clickEvent(event){
        const e = event || window.event || arguments.callee.caller.arguments[0]
        if(!e) return
        let but= e.button;
        if (but===0){
          this.contextMenuVisible=false;
        }
      },

      handleCommand(command) {
        if (command==='exit'){
          let _this=this;
          _this.$confirm('是否退出系统', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.loginOut();
          }).catch(() => {

          });
        }
        if (command==='resetPwd'){
          this.openPwd();
        }
      },
      async loginCheck(){
        let _this=this;
        let url="/loginCheck"
        let params={token:this.$store.state.sessionUser.token};
        await _this.$http.post(url,params).then(function(res){
          if(res.data.success){
            //
          }else{
            _this.$message.error('登录失效');
            _this.$router.push({ path: _this.$store.state.loginPath });
          }
        },function(e){
          _this.$message.error('操作错误！'+e);
          _this.$router.push({ path: _this.$store.state.loginPath });
        });
      },

      findMenuByPath(path,menuList){
        for (let key in menuList) {
          let menu=menuList[key];
          if (menu.fullUrl===path){
            return menu;
          }
          if (menu.children && menu.children.length>0){
            let cMenu=this.findMenuByPath(path,menu.children);
            if (cMenu){
              return cMenu;
            }
          }
        }
        return null
      },

      async loginOut() {
          let _this=this;
          let url="/loginOut"
          let params={};
          await  _this.$http.post(url,params).then(function(res){
            if(res.data.success){
              console.log("退出成功")
            }else{
              _this.$message.error('退出失败 '+res.data.msg);
            }
          },function(e){
            _this.$message.error('操作错误！'+e);
          });
         _this.$router.push({ path: _this.$store.state.loginPath })
      },

      handleOpen(key, keyPath) {
        console.log(key, keyPath);
      },
      handleClose(key, keyPath) {
        console.log(key, keyPath);
      },
      collapseNav(){
        if (this.isNavCollapse){
          this.isNavCollapse=false;
          this.navWidth='200px';
        }else{
          this.isNavCollapse=true;
          this.navWidth='70px';
        }
      },
      toHome(){
        let _this=this;
        let _path="/"+_this.$store.state.homeMenu.appCode+_this.$store.state.homeMenu.path
        this.$router.push({path:_path});
        this.$store.commit('setActiveMenu', JSON.parse(JSON.stringify(this.$store.state.homeMenu)));
      },
      openPwd(){
        this.pwdVisible=true;
        this.$refs.pwdRef.loadData();
      },

      getCompo(path){
        let _this=this;
        let compo='';//根据path在 router里查找 compo;
        let route=_this.$routes.find(item => item.path===path);
        if (route){
          compo=JSON.parse(JSON.stringify(route.meta.compo));
          console.log("get compo",compo);
          _this.$store.commit('addViewIncludes', compo);
        }
        return compo;
      },

    },
    watch:{
      '$store.state.clientHeight':function(){ //监听屏幕高度变化
        let _this=this;
        _this.$actions.setGlobalState({clientHeight:_this.$store.state.clientHeight});
        this.$nextTick(function () {
          _this.$store.dispatch("setConHeightForMain");
          _this.ifmHeight=_this.$store.state.clientHeight-_this.topHeight;
        });
      },
      $route (to,from) {

      }
    }
  }
</script>

<style>
  .base-header, .base-footer {
    background: #0072c6;
    color: #333;
    text-align: left;
    line-height: 30px;
    padding: 0px 20px 0px 10px;
    height: 40px !important;
  }
  .main-container{

  }

  .base-aside {
    color: #333;
    overflow-x:hidden !important;
    text-align: left;

    border-right:solid 1px #e6e6e6;
    background-color:#545c64;
  }

  .base-aside .el-menu{
    border-right: #e6e6e6 !important;
  }

  .base-top-tabs.el-tabs--border-card>.el-tabs__content {
    padding: 0px  !important;
  }
  .base-top-tabs .el-tabs--border-card{
    border:none;
    box-shadow:none;
    padding: 0px !important;
  }
  .base-main {
    background-color: #fff;
    color: #333;
    text-align: left;
    padding: 0px !important;
    overflow: hidden;
  }
  .base-main .el-tabs__item{
    height:35px;
    line-height: 35px;
    padding: 0px 20px;
  }
  .base-main .el-tab-pane{

  }
  .el-menu-item{
    background: #444 !important;
  }
  .el-menu-item.is-active{
    background: rgb(83, 168, 255) !important;
  }

  .base-header .el-dropdown-link {
    cursor: pointer;
    color: #fff;
  }
  .base-header.el-icon-arrow-down {
    font-size: 12px;
  }
  body{
    margin: 0px;
  }


  .contextmenu {
    width: 100px;
    margin: 0;
    border: 1px solid #ccc;
    background: #fff;
    z-index: 3000;
    position: absolute;
    list-style-type: none;
    padding: 5px 0;
    border-radius: 4px;
    font-size: 14px;
    color: #333;
    box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.2);
  }
  .contextmenu li {
    margin: 0;
    padding: 0px 22px;

  }
  .contextmenu li:hover {
    background: #f2f2f2;
    cursor: pointer;
  }
  .contextmenu li button{
    color: #2c3e50;
  }

</style>

